package mil.af.amc.adpetracker.web.actions.EquipmentItem;

import mil.af.amc.adpetracker.exceptions.DateFormatException;
import mil.af.amc.adpetracker.exceptions.EquipmentItemNotFoundException;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.web.actions.AbstractAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Action to Edit (rather than Add) an equipment item
 *
 * @author TSgt Jason Ferguson
 */

public class EditItemAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(EditItemAction.class);

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        DynaActionForm form = (DynaActionForm) actionForm;
        try {
            equipmentItemService.editItem(form.getMap());
        } catch (EquipmentItemNotFoundException e) {

            return actionMapping.getInputForward();

        } catch (DateFormatException e) {
            log.debug(e);
            ActionMessage message = new ActionMessage("Bad Date Format");
            saveMessage(httpServletRequest, message);

            return actionMapping.getInputForward();

        }

        ActionMessage message = new ActionMessage("Item successfully updated.");
        saveMessage(httpServletRequest, message);

        return actionMapping.findForward("success");
    }
}
